package frame.yuangong;

import MyBatis.MyBatislianjian;
import org.apache.ibatis.session.SqlSession;
import org.example.mapper.GoodMapper;
import org.example.pojo.Good;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

// 继承自 JInternalFrame
public class goods extends JInternalFrame {
    private JTable table;
    private DefaultTableModel tableModel;
    private JLabel lblGoodCount; // 声明商品数量标签
    private SqlSession sqlSession = MyBatislianjian.getSqlSession();
    private GoodMapper goodMapper = sqlSession.getMapper(GoodMapper.class);

    // 构造方法
    public goods() {
        super("商品管理界面", true, true, true, true); // 设置内部窗口的标题等属性
        this.setLayout(new BorderLayout()); // 使用边界布局

        // 设置JInternalFrame的大小
        this.setSize(800, 600);

        // 初始化 JTable
        table = new JTable() {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false; // 设置单元格不可编辑
            }
        };
        table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); // 设置多选模式

        // 初始化表格数据
        initializeTableData();

        // 将表格及其滚动面板添加到中心区域
        JScrollPane scrollPane = new JScrollPane(table);
        this.add(scrollPane, BorderLayout.CENTER);

        // 创建按钮面板并添加到 SOUTH 区域
        JPanel buttonPanel = new JPanel(new BorderLayout()); // 使用BorderLayout布局
        this.add(buttonPanel, BorderLayout.SOUTH);

        // 添加商品数量文本标签
        lblGoodCount = new JLabel("商品数量: " + tableModel.getRowCount());
        lblGoodCount.setBorder(BorderFactory.createEmptyBorder(5, 10, 5, 10));
        buttonPanel.add(lblGoodCount, BorderLayout.WEST); // 放在按钮面板的最左侧

        // 创建一个面板用于放置按钮，使用FlowLayout，并设置居中对齐
        JPanel buttonCenterPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        buttonPanel.add(buttonCenterPanel, BorderLayout.CENTER);
        // 导出CSV按钮
        JButton exportButton = new JButton("导出CSV文件");
        exportButton.addActionListener(e -> {
            try {
                exportToCSV();
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        });
        buttonPanel.add(exportButton, BorderLayout.EAST);
    }

    // 初始化表格数据方法，示例中数据为示意，需要替换成实际数据源
    private void initializeTableData() {
        Object[] columnNames = {"商品编号", "商品名称", "商品价格", "客户编号", "商品介绍", "备注"};
        List<Good> goods = goodMapper.selectAll();

        Object[][] data = new Object[goods.size()][columnNames.length];
        for (int i = 0; i < goods.size(); i++) {
            Good good = goods.get(i);
            data[i][0] = good.getGid();
            data[i][1] = good.getGName();
            data[i][2] = good.getGPay();
            data[i][3] = good.getCid();
            data[i][4] = good.getGIntroduction();
            data[i][5] = good.getOther();
        }

        tableModel = new DefaultTableModel(data, columnNames);
        table.setModel(tableModel);

        updateGoodCountLabel(); // 更新商品数量显示
    }

    // 更新商品数量标签方法
    private void updateGoodCountLabel() {
        if (lblGoodCount != null) {
            lblGoodCount.setText("商品数量: " + tableModel.getRowCount());
        }
    }

    // 刷新表格数据方法，示例中为重新从数据库获取数据刷新表格
    private void refreshTableData() {
        List<Good> goods = goodMapper.selectAll();

        tableModel.setRowCount(0);

        for (Good good : goods) {
            tableModel.addRow(new Object[]{
                    good.getGid(),
                    good.getGName(),
                    good.getGPay(),
                    good.getCid(),
                    good.getGIntroduction(),
                    good.getOther()
            });
        }

        updateGoodCountLabel(); // 更新商品数量显示
    }

    // 导出CSV文件方法
    private void exportToCSV() throws IOException {
        // 提示用户输入文件名
        String suggestedFileName = JOptionPane.showInputDialog(this, "请输入要导出的文件名（不包含扩展名.csv）:");

        if (suggestedFileName == null || suggestedFileName.trim().isEmpty()) {
            JOptionPane.showMessageDialog(this, "文件名不能为空！", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        // 设置导出文件的目录为绝对路径（例如：C:/Users/冉前辉/Desktop）
        File defaultDir = new File("C:/Users/冉前辉/Desktop");

        // 构造完整的文件名，确保以用户输入的文件名开头，添加 .csv 扩展名
        String fileName = suggestedFileName.trim() + ".csv";
        File fileToSave = new File(defaultDir, fileName);

        try (FileWriter fw = new FileWriter(fileToSave)) {
            // 写入表头
            for (int i = 0; i < tableModel.getColumnCount(); i++) {
                fw.append(tableModel.getColumnName(i));
                if (i < tableModel.getColumnCount() - 1) {
                    fw.append(",");
                } else {
                    fw.append("\n");
                }
            }

            // 写入数据
            for (int row = 0; row < tableModel.getRowCount(); row++) {
                for (int col = 0; col < tableModel.getColumnCount(); col++) {
                    fw.append(String.valueOf(tableModel.getValueAt(row, col)));
                    if (col < tableModel.getColumnCount() - 1) {
                        fw.append(",");
                    } else {
                        fw.append("\n");
                    }
                }
            }

            JOptionPane.showMessageDialog(this, "CSV文件已成功导出至:\n" + fileToSave.getAbsolutePath(), "导出成功", JOptionPane.INFORMATION_MESSAGE);
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(this, "导出CSV文件时发生错误：" + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

}
